package com.jintoufs.web.action.hotel;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.jhj.common.util.JhjResponseUtil;
import com.jintoufs.dao.QueryFilters;
import com.jintoufs.dao.QueryRule;
import com.jintoufs.domain.customer.Customer;
import com.jintoufs.domain.hotel.Hotel;
import com.jintoufs.domain.region.Region;
import com.jintoufs.domain.shop.Shop;
import com.jintoufs.domain.shop.ShopManager;
import com.jintoufs.domain.user.User;
import com.jintoufs.logAnnotation.SystemControllerLog;
import com.jintoufs.service.customer.CustomerService;
import com.jintoufs.service.hotel.HotelService;
import com.jintoufs.service.region.RegionService;
import com.jintoufs.service.shop.ShopManagerService;
import com.jintoufs.service.shop.ShopService;
import com.jintoufs.util.valid.ValidUtil;
import com.jintoufs.util.ztree.TreeNode;
import com.jintoufs.web.action.shiro.bind.annotation.CurrentUser;
import com.jintoufs.web.action.support.JqgridPage;
import com.jintoufs.web.action.support.SupportAction;
import org.cosmos.modules.web.msg.AjaxMsg;
import org.springframework.context.annotation.Scope;
import org.springframework.dao.DataIntegrityViolationException;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by xufei on 2017/12/29.
 */
@Controller
@Scope("prototype")
@RequestMapping("/hotels")
public class HotelAction extends SupportAction{

    @Resource
    private HotelService hotelService;

    @Resource
    private RegionService regionService;

    @Resource
    private CustomerService customerService;

    @Resource
    private ShopService shopService;

    @Resource
    private ShopManagerService shopManagerService;
    /**
     * 酒店信息查询
     * @return
     * @throws IOException
     */
    @RequestMapping("/list")
    public String list() {
        return "hotels/list";
    }

    @RequestMapping("/authlist")
    public String authList() {
        return "hotels/authlist";
    }

    @RequestMapping("/query")
    @ResponseBody
    @SystemControllerLog(description = "获取酒店列表")
    public JqgridPage query(String status,String op,int page, int rows, String sidx, String sord, String filters) {
        PageHelper.startPage(page, rows);
        QueryFilters filters_ = null;
        if (filters == null || filters.trim().isEmpty()) {
            filters_ = new QueryFilters();
        } else {
            filters_ = JSON.parseObject(filters, QueryFilters.class);
        }
        if (!ValidUtil.isEmpty(status)){
            QueryRule role = new QueryRule();
            role = new QueryRule();
            role.setOp(op);
            role.setField("h.status");
            role.setData(status);
            filters_.getRules().add(role);
        }
        filters_.setSidx(sidx);
        filters_.setSord(sord);
        List<Map<String,Object>> list = hotelService.getByFilter(filters_);
        // 用PageInfo对结果进行包装
        PageInfo pageInfo = new PageInfo(list);
        return new JqgridPage(pageInfo.getTotal(), pageInfo.getPages(), pageInfo.getPageNum(),
                pageInfo.getList());
    }

    /**
     * input.do?id= 进入活动编辑与新增页面 <br>*
     * @param id    活动Id
     * @param model
     * @return
     */
    @RequestMapping(value = "input", method = RequestMethod.GET)
    public String input(String id, Model model) {
        Map<String,Object> entity = null;
        Region region = null;
        Map map = new HashMap();
        // 是否为编辑保存
        Boolean isEdit = false;

        if (id != null) {
            // 修改
            Map<String, Object> params = new HashMap<String, Object>();
            params.put("id", id);
            List<Map<String,Object>> list = hotelService.findByHotel(params);

            if (list != null && list.size() > 0) {
                entity = list.get(0);
                region = regionService.queryById(Short.valueOf(entity.get("regionId").toString()));
            }
            isEdit = true;
        } else {
            // 新增
        }

        List<TreeNode> list = regionService.getModuleTree(region);
        model.addAttribute("ztreeNodes",JSON.toJSONString(list));
        model.addAttribute("isEdit", isEdit);
        model.addAttribute("entity", entity);
        return "hotels/input";
    }

    @RequestMapping(value = "add", method = RequestMethod.POST)
    @SystemControllerLog(description = "新增酒店")
    public void save(Hotel hotel, HttpServletResponse response, @CurrentUser User user) throws ParseException {
        String id = null;
        String error = null;
        if(hotel.getHotelName() == null && "".equals(hotel.getHotelName())){
            error = "酒店名字不能为空！";
        }
        if(hotel.getAddress() == null && "".equals(hotel.getAddress())){
            error = "详细地址不能为空！";
        }
        if (ValidUtil.isEmpty(hotel.getId())){
            DateFormat format=new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            String time=format.format(new Date());
            hotel.setCreateTime(format.parse(time));
            hotel.setModifyTime(format.parse(time));
            id = getUUID();
        }
        hotel.setCreateUserId(user.getId().toString());
        Map<String, Object>  result = hotelService.save(hotel,id);
        JhjResponseUtil.responseJson(response, JSON.toJSONString(result));
    }


    @RequestMapping("edit")
    @SystemControllerLog(description = "修改酒店信息")
    public void edit(Hotel hotel, HttpServletResponse response) {
        Map<String, Object> result = hotelService.save(hotel,null);
        JhjResponseUtil.responseJson(response, JSON.toJSONString(result));
    }



    @RequestMapping("delete")
    @SystemControllerLog(description = "删除酒店信息")
    public void delete(HttpServletResponse response, String[] id) {
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {
            for (String _id:id){
                hotelService.delete(_id);

            }
        } catch (Exception e) {
            e.printStackTrace();
            if (e instanceof DataIntegrityViolationException) {
                ajaxMsg.setCode("500");
                ajaxMsg.setMessage("该酒店还在营业中，删除失败！");
            }
        }
        writeInfo(response, JSON.toJSONString(ajaxMsg));
    }

    /**
     * 获取详细信息
     */
    @RequestMapping("/getDetail")
    @SystemControllerLog(description = "查看酒店详细信息")
    public String getDetail(String id, Model model) {
        Map<String,Object> result = new HashMap<>();
        if (!ValidUtil.isEmpty(id)) {
            result = hotelService.getById(id);
        }
        model.addAttribute("entity", result);
        model.addAttribute("isEdit", "view");
        model.addAttribute("title", "酒店详细信息");
        return "hotels/detail";
    }

    @RequestMapping("/setAdmin")
    @ResponseBody
    public AjaxMsg setAdmin(String mobilePhone,String hotelId){
        int error = 0;
        String errorMessage="";
        AjaxMsg ajaxMsg = new AjaxMsg();
        Map<String,Object> param = new HashMap<>();
        param.put("mobilePhone",mobilePhone);
        param.put("valueId",hotelId);
        try {
            List<Shop> shops = shopService.selectByParam(param);
            if (shops.size()==0){
                Customer customer = customerService.queryByParams(param).get(0);
                if (customer ==null){
                    error++;
                    errorMessage = "没有找到对应供应商用户";
                }else {
                    Shop shop = new Shop();
                    shop.setValueId(hotelId);
                    Shop now = shopService.save(shop,getUUID());
                    ShopManager shopManager = new ShopManager();
                    shopManager.setShopId(now.getId());
                    shopManager.setCustomerId(customer.getId());
                    shopManagerService.save(shopManager,getUUID());
                    errorMessage = "设置成功。";
                }
            }else {
                error++;
                errorMessage = "已经设置过啦！";
            }
        }catch (Exception e){
            e.printStackTrace();
            error++;
            errorMessage = "系统异常。";
        }
        if (error !=0){
            ajaxMsg.setCode("500");
            ajaxMsg.setMessage(errorMessage);
        }
        return ajaxMsg;
    }

    @RequestMapping("unlock")
    @ResponseBody
    public AjaxMsg unlock(String id){
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {
            Hotel hotel=hotelService.selectByPrimaryKey(id);
            if("0".equals(hotel.getStatus())){
                hotel.setStatus("1");
            }else{
                hotel.setStatus("0");
            }
            hotelService.update(hotel);
            ajaxMsg.setMessage("操作成功。");
        }catch (Exception e){
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage("操作失败");
        }
        return ajaxMsg;
    }

    @RequestMapping("unUse")
    @ResponseBody
    public AjaxMsg unUse(String id){
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {
            Hotel hotel=hotelService.selectByPrimaryKey(id);
            if("0".equals(hotel.getInUse())){
                hotel.setInUse("1");
            }else{
                hotel.setInUse("0");
            }
            hotelService.update(hotel);
            ajaxMsg.setMessage("操作成功。");
        }catch (Exception e){
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage("操作失败");
        }
        return ajaxMsg;
    }
    @RequestMapping("setRecommend")
    @ResponseBody
    public AjaxMsg setRecommend(String id){
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {
            Hotel hotel=hotelService.selectByPrimaryKey(id);
            if("0".equals(hotel.getRecommend())){
                hotel.setRecommend("1");
            }else{
                hotel.setRecommend("0");
            }
            hotelService.update(hotel);
            ajaxMsg.setMessage("操作成功。");
        }catch (Exception e){
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage("操作失败");
        }
        return ajaxMsg;
    }

    @RequestMapping("auth")
    @ResponseBody
    public AjaxMsg auth(String id,String type){
        AjaxMsg ajaxMsg = new AjaxMsg();
        try {
            hotelService.auth(id,type);
            ajaxMsg.setMessage("操作成功。");
        }catch (Exception e){
            e.printStackTrace();
            ajaxMsg.setCode(AjaxMsg.FAILURE);
            ajaxMsg.setMessage("操作失败");
        }
        return ajaxMsg;
    }
}
